package com.ynwa;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * adder 和 atomic
 *
 * @author gzd
 * @date 2019-11-03 21:55
 */
public class AtomicVsAdder {

    public static void atomicInteger() throws InterruptedException {
        AtomicInteger atomicInteger = new AtomicInteger();
        long l = System.currentTimeMillis();

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 100000000; j++) {
                    atomicInteger.incrementAndGet();
                }
            }, "thread " + i);
            thread.start();
            thread.join();
        }


        long l1 = System.currentTimeMillis();

        Thread.sleep(30000);
        System.out.println(l1 - l);
        System.out.println(atomicInteger.get());
    }

    public static void adder() throws InterruptedException {
        LongAdder longAdder = new LongAdder();
        long l = System.currentTimeMillis();

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100000000; j++) {
                    longAdder.increment();
                }
            }, "thread " + i).start();
        }

        long l1 = System.currentTimeMillis();

        Thread.sleep(3000);
        System.out.println(l1 - l);
        System.out.println(longAdder.longValue());
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("begin");
//        adder();
        atomicInteger();
    }
}
